package com.jt.demo1.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxy {
    //工具API，目的获取代理对象
    public static Object getProxy(Object target){
        //获取目标对象的类加载器
        ClassLoader Loader = target.getClass().getClassLoader();
        //获取接口数组
        Class<?>[] interfaces = target.getClass().getInterfaces();
        //获取处理器对象
        InvocationHandler h=getInvocationHandler(target);
        //创建代理对象
        return Proxy.newProxyInstance(Loader, interfaces,h);
    }
        public static InvocationHandler getInvocationHandler(Object target){
            return new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("事务开始");
                    //让目标方法执行
                    Object result = method.invoke(target, args);
                    System.out.println("事务提交");
                    return result;
            }
        };
    }
}
